const { checkAuth } = require('../../utils/auth.js')
const { getApiUrl } = require('../../config/config.js')
Page({
  data: {
    posts: [],
    loading: false,
    refreshing: false,
    hasMore: true,
    page: 1,
    pageSize: 10,
    currentTab: 0, // 当前选中的标签
    currentCategory: 0, // 当前选中的分类标签
    scrollPosition: 0, // 记录滚动位置
    lastScrollPosition: 0, // 记录上次离开页面时的滚动位置
    keepScrollPosition: false, // 是否保持滚动位置
    scrollPositionToRestore: 0, // 需要恢复的滚动位置
    banners: [
      '/images/header/banner1.jpg',
      '/images/header/banner2.jpg',
      '/images/header/banner3.jpg',
      '/images/header/banner4.jpg',
      '/images/header/banner5.jpg',
      '/images/header/banner6.jpg'
    ],
    categories: [
      { id: 0, name: '综合' },
      { id: 1, name:'校园公告'},
      { id: 2, name: '学术学习' },
      { id: 3, name: '校园生活' },
      { id: 4, name: '社交兴趣' },
      { id: 5, name: '就业实习' },
      { id: 6, name: '校园服务' }
    ],
    functions: [
      { id: 1, name: '每日小记', icon: '/images/icon_index/day.png' },
      { id: 2, name: '校园活动', icon: '/images/icon_index/activity.png' },
      { id: 3, name: '失物招领', icon: '/images/icon_index/lost_found.png' },
      { id: 4, name: '心理治愈', icon: '/images/icon_index/psychology.png' },
      { id: 5, name: '学习资源', icon: '/images/icon_index/study.png' },
      { id: 6, name: '考试助手', icon: '/images/icon_index/exam_helper.png' },
      { id: 7, name: '智能食堂', icon: '/images/icon_index/smart_canteen.png' },
      { id: 8, name: '宿舍助手', icon: '/images/icon_index/dorm_assistant.png' },
      { id: 9, name: '活动策划', icon: '/images/icon_index/activity_planner.png' },
      { id: 10, name: '生涯规划', icon: '/images/icon_index/career_guide.png' },
    ],
    likeDebounce: false, // 添加防抖标记
    likedPostIds: [] // 存储用户点赞的帖子ID
  },

  onLoad() {
    // 从本地存储加载点赞状态
    this.loadLikedPosts()
    
    // 加载帖子列表
    this.loadPosts(true)
  },

  onShow() {
    // 从本地存储加载点赞状态
    this.loadLikedPosts()
    
    // 检查是否需要刷新
    const app = getApp()
    if (app.globalData.needRefreshPosts) {
      const { type, timestamp } = app.globalData.needRefreshPosts
      // 清除刷新标记
      app.globalData.needRefreshPosts = null
      
      // 切换到对应标签并刷新
      this.setData({
        currentTab: type,
        posts: [],
        page: 1,
        hasMore: true
      }, () => {
        this.loadPosts(true)
      })
    }

    // 当从其他页面返回时，恢复滚动位置
    if (this.data.lastScrollPosition > 0) {
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: this.data.lastScrollPosition,
          duration: 0
        });
      }, 100);
    }
  },

  onHide() {
    // 保存离开页面时的滚动位置
    this.setData({
      lastScrollPosition: this.data.scrollPosition
    });
  },

  // 加载用户点赞的帖子ID
  loadLikedPosts() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) return
    
    const userId = userInfo.id
    const likedPosts = wx.getStorageSync('likedPosts') || {}
    const likedPostIds = likedPosts[userId] || []
    
    console.log('加载用户点赞状态:', likedPostIds)
    
    this.setData({ likedPostIds })
    
    // 更新当前帖子列表的点赞状态
    if (this.data.posts.length > 0) {
      const updatedPosts = this.data.posts.map(post => {
        return {
          ...post,
          isLiked: likedPostIds.includes(post.id)
        }
      })
      
      this.setData({ posts: updatedPosts })
    }
  },

  // 保存用户点赞的帖子ID
  saveLikedPosts() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) return
    
    const userId = userInfo.id
    let likedPosts = wx.getStorageSync('likedPosts') || {}
    
    likedPosts[userId] = this.data.likedPostIds
    
    console.log('保存用户点赞状态:', likedPosts)
    
    wx.setStorageSync('likedPosts', likedPosts)
  },

  // 切换标签
  onTabChange(e) {
    const tabId = e.currentTarget.dataset.id
    if (tabId === this.data.currentTab) return
    
    this.setData({
      currentTab: tabId,
      posts: [],
      page: 1,
      hasMore: true
    }, () => {
      this.loadPosts()
    })
  },

  onPullDownRefresh() {
    this.setData({
      posts: [],
      page: 1,
      hasMore: true,
      refreshing: true
    }, () => {
      this.loadPosts(true).then(() => {
        wx.stopPullDownRefresh()
      })
    })
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadPosts()
    }
  },

  // 展开帖子全文
  expandPost(e) {
    const index = e.currentTarget.dataset.index
    const posts = this.data.posts
    posts[index].isExpanded = true
    this.setData({ posts })
  },

  // 预览图片
  previewImage(e) {
    const { urls, current } = e.currentTarget.dataset
    wx.previewImage({
      urls,
      current
    })
  },

  // 点赞
  async onTapLike(e) {
    // 检查用户是否登录
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    // 防抖处理
    if (this.data.likeDebounce) return
    this.setData({ likeDebounce: true })

    const { id, index } = e.currentTarget.dataset
    const userId = userInfo.id
    
    // 检查是否已点赞
    const isLiked = this.data.posts[index].isLiked
    
    // 获取本地存储的点赞记录
    let likedPosts = wx.getStorageSync('likedPosts') || {}
    if (!likedPosts[userId]) {
      likedPosts[userId] = []
    }
    
    // 更新本地存储
    if (isLiked) {
      // 取消点赞，从数组中移除
      likedPosts[userId] = likedPosts[userId].filter(postId => postId !== id)
    } else {
      // 点赞，添加到数组
      if (likedPosts[userId].indexOf(id) === -1) {
        likedPosts[userId].push(id)
      }
    }
    
    // 保存到本地存储
    wx.setStorageSync('likedPosts', likedPosts)
    
    // 乐观更新UI
    this.setData({
      [`posts[${index}].isLiked`]: !isLiked,
      [`posts[${index}].likesCount`]: isLiked 
        ? Math.max(0, this.data.posts[index].likesCount - 1) 
        : (this.data.posts[index].likesCount || 0) + 1
    })
    
    wx.showLoading({ title: '处理中...', mask: true })
    
    try {
      // 发送点赞请求
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/post/like/${id}/${userId}`),
          method: 'POST',
          header: {
            'token': wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        })
      })

      if (res.data.code === 200) {
        const { status, totalLikes } = res.data.data
        
        // 更新首页列表中的点赞状态
        this.setData({
          [`posts[${index}].isLiked`]: status === 1,
          [`posts[${index}].likesCount`]: totalLikes
        })
        
        // 根据服务器返回的状态更新本地存储
        if (status === 1) {
          // 确保帖子ID在点赞列表中
          if (likedPosts[userId].indexOf(id) === -1) {
            likedPosts[userId].push(id)
          }
        } else {
          // 确保帖子ID不在点赞列表中
          likedPosts[userId] = likedPosts[userId].filter(postId => postId !== id)
        }
        
        // 再次保存到本地存储
        wx.setStorageSync('likedPosts', likedPosts)

        // 同时更新详情页的点赞状态（如果在详情页）
        const pages = getCurrentPages()
        const detailPage = pages.find(p => p.route === 'pages/details/details')
        if (detailPage && detailPage.data.post.id === id) {
          detailPage.setData({
            'post.isLiked': status === 1,
            'post.likesCount': totalLikes
          })
        }

        wx.showToast({
          title: status === 1 ? '点赞成功' : '已取消点赞',
          icon: 'success'
        })
      } else {
        // 如果请求失败，回滚UI和本地存储
        if (isLiked) {
          // 恢复点赞
          if (likedPosts[userId].indexOf(id) === -1) {
            likedPosts[userId].push(id)
          }
        } else {
          // 恢复取消点赞
          likedPosts[userId] = likedPosts[userId].filter(postId => postId !== id)
        }
        wx.setStorageSync('likedPosts', likedPosts)
        
        this.setData({
          [`posts[${index}].isLiked`]: isLiked,
          [`posts[${index}].likesCount`]: this.data.posts[index].likesCount + (isLiked ? 1 : -1)
        })
        
        wx.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('Like failed:', error)
      
      // 发生错误时回滚UI和本地存储
      if (isLiked) {
        // 恢复点赞
        if (likedPosts[userId].indexOf(id) === -1) {
          likedPosts[userId].push(id)
        }
      } else {
        // 恢复取消点赞
        likedPosts[userId] = likedPosts[userId].filter(postId => postId !== id)
      }
      wx.setStorageSync('likedPosts', likedPosts)
      
      this.setData({
        [`posts[${index}].isLiked`]: isLiked,
        [`posts[${index}].likesCount`]: this.data.posts[index].likesCount + (isLiked ? 1 : -1)
      })
      
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
      // 重置防抖标记
      setTimeout(() => {
        this.setData({ likeDebounce: false })
      }, 1000)
    }
  },

  // 评论
  onTapComment(e) {
    const id = e.currentTarget.dataset.id
    wx.showToast({
      title: '评论功能开发中',
      icon: 'none'
    })
  },

  // 分享
  onTapShare(e) {
    const id = e.currentTarget.dataset.id
    wx.showToast({
      title: '分享功能开发中',
      icon: 'none'
    })
  },

  // 加载帖子列表
  async loadPosts(isRefresh = false) {
    return new Promise(async (resolveFn, rejectFn) => {
      try {
        // 如果是刷新则重置页码为1
        if (isRefresh) {
          this.setData({
            page: 1,
            hasMore: true,
            refreshing: true,
            loading: false  // 确保refreshing和loading不同时为true
          })
        } else {
          // 如果是加载更多，则设置loading而不是refreshing
          this.setData({ loading: true })
        }
        
        // 如果没有更多数据则直接返回
        if (!this.data.hasMore && !isRefresh) {
          return
        }
        
        const { page, pageSize, currentCategory } = this.data
        
        // 根据当前选中的分类构建请求URL
        let url
        if (currentCategory === 0) {
          // 如果是综合分类，则使用 /post/list 接口
          url = getApiUrl(`/post/list?page=${page}&pageSize=${pageSize}`)
        } else {
          // 如果是其他分类，则使用 /post/list/type/{categoryId} 接口
          url = getApiUrl(`/post/list/type/${currentCategory}?page=${page}&pageSize=${pageSize}`)
        }

        const response = await new Promise((resolve, reject) => {
          wx.request({
            url,
            method: 'GET',
            success: (res) => resolve(res),
            fail: (err) => reject(err)
          })
        })

        if (response && response.data && response.data.code === 200) {
          // 处理帖子数据
          const processPosts = (posts) => {
            if (!posts || !posts.length) return [];
            
            return posts.map(post => {
              // 处理图片列表
              const imageList = [];
              for (let i = 1; i <= 9; i++) {
                const imgKey = `image${i}`;
                if (post[imgKey]) {
                  imageList.push(post[imgKey]);
                }
              }
              
              // 处理创建时间
              let createTime = '';
              if (post.createTime) {
                const date = new Date(post.createTime);
                createTime = this.formatTime(date);
              }
              
              // 处理标签 - 确保标签是数组
              const tags = Array.isArray(post.tags) ? post.tags : [];
              
              return {
                ...post,
                imageList,
                createTime,
                tags,
                isLiked: this.data.likedPostIds.includes(post.id)
              };
            });
          }

          // 处理数据
          let newPosts = []
          if (this.data.currentTab === 0) {
            // 综合标签数据处理
            newPosts = processPosts(response.data.data)
          } else {
            // 其他标签数据处理
            const posts = Array.isArray(response.data.data) ? response.data.data : []
            newPosts = processPosts(posts)
          }

          this.setData({
            posts: isRefresh ? newPosts : [...this.data.posts, ...newPosts],
            hasMore: newPosts.length === this.data.pageSize,
            page: isRefresh ? 2 : this.data.page + 1
          })
          
          // 检查是否需要恢复滚动位置
          if (this.data.keepScrollPosition && this.data.scrollPositionToRestore) {
            // 使用更长的延迟，确保渲染完成
            setTimeout(() => {
              wx.pageScrollTo({
                scrollTop: this.data.scrollPositionToRestore,
                duration: 0
              });
              // 重置标记
              this.setData({
                keepScrollPosition: false,
                scrollPositionToRestore: 0
              });
            }, 500);
          }
          
          resolveFn();
        } else {
          throw new Error('加载失败')
        }
      } catch (error) {
        console.error('加载帖子失败:', error)
        wx.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
        rejectFn(error);
      } finally {
        this.setData({
          loading: false,
          refreshing: false
        })
      }
    })
  },

  // 格式化时间为相对时间
  formatTime(date) {
    if (!date) return '';
    
    const now = new Date();
    const diff = now - date; // 毫秒差
    
    // 刚刚（1分钟内）
    if (diff < 60 * 1000) {
      return '刚刚';
    }
    
    // x分钟前（1小时内）
    if (diff < 60 * 60 * 1000) {
      return Math.floor(diff / (60 * 1000)) + '分钟前';
    }
    
    // x小时前（24小时内）
    if (diff < 24 * 60 * 60 * 1000) {
      return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
    }
    
    // x天前（7天内）
    if (diff < 7 * 24 * 60 * 60 * 1000) {
      return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前';
    }
    
    // 超过7天显示具体日期
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    
    // 如果是今年，只显示月-日
    if (year === now.getFullYear()) {
      return `${month}-${day}`;
    }
    
    // 不是今年，显示年-月-日
    return `${year}-${month}-${day}`;
  },

  // 点击帖子跳转到详情页
  onTapPost(e) {
    const { id, index } = e.currentTarget.dataset
    const post = this.data.posts[index]
    
    if (post) {
      // 将帖子数据序列化后传递给详情页
      const postStr = encodeURIComponent(JSON.stringify(post))
      wx.navigateTo({
        url: `/pages/details/details?id=${id}&post=${postStr}`,
        fail: (err) => {
          console.error('Navigation failed:', err)
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    }
  },

  // 点击发帖按钮
  onTapPostBtn() {
    wx.switchTab({
      url: '/pages/post/post',
    })
  },

  // 点击用户头像
  onTapUser(e) {
    const { userId } = e.currentTarget.dataset
    if (userId) {
      wx.navigateTo({
        url: `/pages/user/user?id=${userId}`
      })
    }
  },

  // 添加点击作者事件处理
  onTapAuthor(e) {
    
    const { id, isAnonymous } = e.currentTarget.dataset

    if (isAnonymous) {
      wx.showToast({
        title: '无法查看匿名用户信息',
        icon: 'none'
      })
      return
    }

    wx.navigateTo({
      url: `/pages/user/user?id=${id}`,
      fail: (err) => {
        console.error('Navigation failed:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  // 点击搜索按钮
  onTapSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },

  // 点击二维码按钮
  onTapQrcode() {
    wx.showToast({
      title: '二维码功能开发中',
      icon: 'none'
    })
  },

  // 点击功能区项目
  onTapFunction(e) {
    const funcId = e.currentTarget.dataset.id;
    
    // 根据功能 ID 跳转到对应页面
    switch (funcId) {
      case 1: // 每日小记
        wx.navigateTo({
          url: '/pages/school_friend/school_friend',
        });
        break;
      case 2: // 校园活动
        wx.navigateTo({
          url: '/pages/activity/activity',
        });
        break;
      case 3: // 失物招领
        wx.navigateTo({
          url: '/pages/lost_found/lost_found',
        });
        break;
      case 4: // 心理治愈
        wx.navigateTo({
          url: '/pages/school_consultation/school_consultation',
        });
        break;
      case 5: // 学习资源
        wx.navigateTo({
          url: '/pages/study/study',
        });
        break;
      case 6: // 考试助手
        wx.navigateTo({
          url: '/pages/exam_helper/exam_helper',
        });
        break;
      case 7: // 智能食堂
        wx.navigateTo({
          url: '/pages/smart_canteen/smart_canteen',
        });
        break;
      case 8: // 宿舍助手
        wx.navigateTo({
          url: '/pages/dorm_assistant/dorm_assistant',
        });
        break;
      case 9: // 活动规划
        wx.navigateTo({
          url: '/pages/activity_planner/activity_planner',
        });
        break;
      case 10: // 学业生涯规划
        wx.navigateTo({
          url: '/pages/career_guide/career_guide',
        });
        break;
      default:
        // 如果没有对应页面，可以显示提示信息
        wx.showToast({
          title: 'AI功能开发中',
          icon: 'none'
        });
    }
  },

  // 点击分类标签 (修改后 - 简化逻辑)
  onCategoryChange(e) {
    const id = e.currentTarget.dataset.id;
    if (id === this.data.currentCategory) return;

    // 更新当前选中的分类
    this.setData({
      currentCategory: id,
      posts: [], // 清空现有帖子
      page: 1,   // 重置页码
      hasMore: true, // 重置加载状态
      loading: false, // 确保loading状态正确
      refreshing: false // 确保refreshing状态正确
    }, () => {
      // 直接调用 loadPosts 强制刷新
      this.loadPosts(true); 
    });
  },
})
